(function() {
	'use strict';
	
	var Step = function(options) {
		var _default = {
            stepInst: null,
            stepInstLabel: null,
            stepType: null,
            groupType: null,
            stepCfg: null,
            stepSeq: null,
            stepIcon: null,
            stepState: '1',
            stepStyle: null
        }
		return _.extend(_default, options);
	}
	
	var store = new Vuex.Store({
	    state: {
	    	steps: []
	    },
	    mutations: {
	    	setSteps: function(state, steps) {
	    		state.steps = steps;
	    	},
		    addStep: function(state, step) {
		        state.steps.push(step);
		    },
		    deleteStep: function(state, step) {
	            state.steps.splice(state.steps.indexOf(step), 1);
		    },
		    editStep: function(state, para) {
		    	para.step = _.extend(para.step, para.options);
		    }
	    }
	});
	
	var stepVue = new Vue({
		el: '#main',
		store: store,
		data: function() {
			return {
				formData: {},
				filterData: {
                    stepInstLabel: "",
					pageNum: 1,
					pageSize: 50
				},
				selectedData: [],
				activeRow: null,
				stateOptions: {'0': '失效', '1': '有效'},
				titles: {'add': '新增指令', 'edit': '编辑指令'},
				total: 0,
				oper: null,
				dialogFormVisible: false,
				tableLoading: false,
				ruleFormRules: {
					stepSeq: [
			           { required: true, message: '序号不能为空'}, 
			           { type: 'number', message: '序号必须为数字值'}
			        ]
				},
				groupOptions: {
					'controlCmd': '控制指令',
					'batchExtract': '批量抽取',
					'batchLoad': '批量加载',
					'batchTransfer': '批量转换',
					'rowLevelExtract': '行级抽取',
					'rowLevelLoad': '行级加载',
					'rowLevelTransfer': '行级转换',
					'check': '校验'
				},
				codeMirrorOption: {
		            mode: 'javascript'
		        },
		        tableHeight: 0
			}
		},
		computed: {
			dialogTitle: function(){
				return this.titles[this.oper]
			},
			tableData: function(){
				return this.$store.state.steps;
			}
		},
		methods: {
			getStepData: function() {
				var self = this;
				axios.get(_contextPath + '/open/datastash/stepdefine/all',
                    {
                        params: {
                            stepInstLabel: self.filterData.stepInstLabel,
                            pageNum: self.filterData.pageNum - 1,
                            pageSize: self.filterData.pageSize,
                            type: [1,2,3]
                        }
                    }
				)
				.then(function (response) {
					if (response.data) {
						self.$store.commit('setSteps', response.data.content);
                        self.total = response.data.totalElements;
                        self.$nextTick(function() {
                        	self.$refs['scrollContent'].resize();
                        }) 
					}
				})
			},
			handleSearch: function() {
                this.getStepData();
			},
			handleSizeChange: function(val) {
				this.filterData.pageSize = val;
                this.getStepData();
            },
			handleCurrentChange: function(val) {
				this.filterData.pageNum = val;
                this.getStepData();
            },
			handleAdd: function() {
				this.oper = 'add';
				this.formData = new Step();
				this.dialogFormVisible = true;
			},
			handleDelete: function(idx,row) {
				var _self = this;
				this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
		            confirmButtonText: '确定',
		            cancelButtonText: '取消',
		            type: 'warning'
		        }).then(function() {
                    axios.post(_contextPath + '/open/datastash/stepdefine/' + row.stepInst+'/delete')
                        .then(function (response) {
                            if(response.data.success){
                                _self.$message({type: 'success', message: '删除成功!'});
                                _self.getStepData();
                            }else{
                                _self.$message({type: 'info', message: '删除失败'});
                            }
                        })
                        .catch(function (error) {
                        });


		        }).catch(function() {
		            _self.$message({type: 'info', message: '已取消删除'});
		        });
			},
			handleEdit: function(row) {
				this.oper = "edit";
				this.activeRow = row;
				var row = _.extend({}, row);
				window.row = row;
				if (row.stepCfg) {
					row.stepCfg = js_beautify(row.stepCfg);
				}
				this.formData = new Step(row);
				this.dialogFormVisible = true;
			},
			handleSelectionChange: function(val) {
	            this.selectedData = val
			},
			stateFormat: function(row) {
				return this.stateOptions[row.stepState];
			},
			handleCancel: function() {
				this.dialogFormVisible = false;
			},
			iGetInnerText: function(testStr) {
		        var resultStr = testStr.replace(/\ +/g, "");
		        resultStr = testStr.replace(/[ ]/g, "");
		        resultStr = testStr.replace(/[\r\n]/g, "");
		        resultStr = testStr.replace(/\s+/g," ")
		        return resultStr;
		    },
			handleSave: function() {
				var _self = this;
				this.$refs['validateForm'].validate(function(valid) {
					if(valid){
						try {
							var jsonStr = null;
							eval('jsonStr = ' + _self.iGetInnerText(_self.formData.stepCfg));
							_self.formData.stepCfg = jsonToString(jsonStr);
						} catch (e) {
							_self.formData.stepCfg = null;
						} 
						if (_self.oper == 'add') {
							_self.$store.commit("addStep", _self.formData);
						}else{
							_self.$store.commit("editStep", {step: _self.activeRow, options: _self.formData});
						}
                        var stepdefine = _.extend({},_self.formData);
                        axios.post(_contextPath+'/open/datastash/stepDefine/creator',stepdefine )
                            .then(function (response) {
                                _self.$alert('保存成功！', '提示', {
                                    confirmButtonText: '确定'
                                });
                            })
                            .catch(function (error) {
                                _self.$alert('保存失败！', '提示', {
                                    confirmButtonText: '确定'
                                });
						});

						_self.dialogFormVisible = false;
					}else{
						return false;
					}
				})
			},
			resize: function(size) {
				this.tableHeight = size.innerHeight;
			}
		},
		created: function() {
			this.getStepData();
		}
	})
}())